﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Configuration;
using Microsoft.Reporting.WinForms;

namespace TMS
{
    public partial class CreateEditReciveNoteControl : UserControl
    {
        Categories cat = new Categories();
        DataSet table = new DataSet();
        Product prod = new Product();
        Partner partner = new Partner();
        Int32 ProductCounter = 0;
         
        Users ActiveUser = Program.GetActiveUser;
        bool edit = false;
        bool init = false;
        bool print = false;
        DateTime Today = DateTime.Today;
        string Responsible;
        int NoteNumber,NoteID;
        DateTime NoteDate = new DateTime();
        string PartnerName;
        string PartnerAddress;
        Int32 Import = 1;
        string Valute;
        Decimal Course;
        string InvoiceNo;
        public Decimal Transport, Spedition, Warehousing, TotalPriceMKD, TotalPriceValute, TotalCustoms, TotalVAT;


        public CreateEditReciveNoteControl()
        {
            Program.GetMainForm.Text = "TMS - Приемници";
            InitializeComponent();


            dgvProductsList.ColumnCount = 10;
            dgvProductsList.Columns[0].HeaderText = "Бр.";
            dgvProductsList.Columns[1].HeaderText = "Бр.на Пр.";
            dgvProductsList.Columns[2].HeaderText = "Име";
            dgvProductsList.Columns[3].HeaderText = "Опис";
            dgvProductsList.Columns[4].HeaderText = "Ед.М.";
            dgvProductsList.Columns[5].HeaderText = "Количина";
            dgvProductsList.Columns[6].Visible = false;
            dgvProductsList.Columns[7].HeaderText = "Магацин";
            dgvProductsList.Columns[8].HeaderText = "Цена";
            dgvProductsList.Columns[9].HeaderText = "Данок";
            dgvProductsList.Columns[0].Width = 30;
            dgvProductsList.Columns[1].Width = 80;
            dgvProductsList.DefaultCellStyle.WrapMode = DataGridViewTriState.True;

            cmbWarehouses.ValueMember = "name";
            cmbVAT.SelectedItem = "18";
            FillWarehouses();
            dgvProductsList.FirstDisplayedScrollingRowIndex = dgvProductsList.RowCount - 1;
        }

        public CreateEditReciveNoteControl(DataGridViewRow row)
        {
            Program.GetMainForm.Text = "TMS - Приемница/Повратница бр.: " + row.Cells[3].Value.ToString();
            edit = true;
            InitializeComponent();
            Valute = row.Cells[10].Value.ToString();
            Transport = Convert.ToDecimal(row.Cells[7].Value.ToString());
            Spedition = Convert.ToDecimal(row.Cells[8].Value.ToString());
            Warehousing = Convert.ToDecimal(row.Cells[9].Value.ToString());
            TotalPriceMKD = 0;
            TotalPriceValute = 0;
            Course =Convert.ToDecimal(row.Cells[11].Value);
            lblValute.Text = "Валута: " + Valute;

            dgvProductsList.ColumnCount = 13;
            dgvProductsList.Columns[0].HeaderText = "Бр.";
            dgvProductsList.Columns[1].HeaderText = "Бр.на Пр.";
            dgvProductsList.Columns[2].HeaderText = "Име";
            dgvProductsList.Columns[3].HeaderText = "Опис";
            dgvProductsList.Columns[4].HeaderText = "Ед.М.";
            dgvProductsList.Columns[5].HeaderText = "Количина";
            dgvProductsList.Columns[6].Visible = false;
            dgvProductsList.Columns[7].HeaderText = "Магацин";
            dgvProductsList.Columns[8].HeaderText = "Цена "+ Valute;
            dgvProductsList.Columns[9].HeaderText = "Данок";
            dgvProductsList.Columns[10].HeaderText = "Царина";
            dgvProductsList.Columns[11].HeaderText = "Влезна цена МКД";
            dgvProductsList.Columns[12].HeaderText = "Вкупна цена МКД";
            dgvProductsList.Columns[0].Width = 30;
            dgvProductsList.Columns[1].Width = 80;
            if (row.Cells[6].Value.ToString() == "0")
            {
                dgvProductsList.Columns[10].Visible = false;
                panelImport.Visible = false;
                Import = 0;
            }
            dgvProductsList.DefaultCellStyle.WrapMode = DataGridViewTriState.True;

            NoteNumber = Convert.ToInt32(row.Cells[3].Value.ToString());
            NoteID = Convert.ToInt32(row.Cells[0].Value.ToString());
            NoteDate = Convert.ToDateTime(row.Cells[1].Value.ToString());
            PartnerName = row.Cells[4].Value.ToString();
            PartnerAddress = partner.GetPartnerAddressByName(row.Cells[4].Value.ToString());
            Responsible = row.Cells[2].Value.ToString();
            InvoiceNo = row.Cells[12].Value.ToString();

            cmbWarehouses.ValueMember = "name";
            cmbVAT.SelectedItem = "18";
            FillWarehouses();
            FillReceiveNoteProductsList(NoteNumber);

            if ((row.Cells[5].Value.ToString() == "Затворена")||(Responsible!=ActiveUser.GetName()+" "+ActiveUser.GetSurname()))
            {
                btnAdd.Visible = false;
                btnEditRemove.Visible = false;
                grbAddProduct.Visible = false;
            }
           
        }

        private void CreateEditReceiveNoteControl_Load(object sender, EventArgs e)
        {
            cmbCategory1.DisplayMember = "name";
            cmbCategory1.ValueMember = "id";
            cmbCategory2.DisplayMember = "name";
            cmbCategory2.ValueMember = "id";
            cmbCategory3.DisplayMember = "name";
            cmbCategory3.ValueMember = "id";
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            object[] product = new object[13];
            ProductCounter = dgvProductsList.Rows.Count + 1;

            Int64 quantity = Convert.ToInt64(txtQuantity.Text);
            DataSet table = new DataSet();
            table = prod.GetProductFromDBAsDataSet(Convert.ToInt32(cmbProductList.SelectedValue));
            product[0] = ProductCounter;
            product[1] = table.Tables[0].Rows[0].ItemArray[5];
            product[2] = table.Tables[0].Rows[0].ItemArray[4].ToString();
            product[3] = table.Tables[0].Rows[0].ItemArray[10];
            product[4] = table.Tables[0].Rows[0].ItemArray[11];
            product[5] = quantity;
            product[6] = table.Tables[0].Rows[0].ItemArray[0];
            product[7] = cmbWarehouses.SelectedValue.ToString();
            product[8] = txtPrice.Text;
            product[9] = cmbVAT.SelectedItem.ToString();
            product[10] = txtCustoms.Text;
            product[11] = "Не е пресметано";
            product[12] = "Не е пресметано";

            if (dgvProductsList.SelectedRows.Count == 0)
                dgvProductsList.Rows.Add(product);
            else
                dgvProductsList.Rows.Insert(dgvProductsList.SelectedRows[0].Index, product);

            Int32 i = 1;
            foreach (DataGridViewRow row in dgvProductsList.Rows)
            {
                row.Cells[0].Value = i;
                i++;
            }
        }

        private void cmbCategory1_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cmbCategory1.Items.Count == 0) cmbCategory1.DataSource = cat.GetAllCategory1().Tables[0];
            else
            {
                if (cmbCategory1.SelectedValue.ToString() == "1")
                {
                    cmbCategory2.DataSource = cat.GetAllCategory2("").Tables[0];
                    cmbCategory3.DataSource = cat.GetAllCategory3("", "").Tables[0];
                }
                else 
                {
                    cmbCategory2.DataSource = cat.GetAllCategory2(cmbCategory1.SelectedValue.ToString()).Tables[0];
                    cmbCategory3.DataSource = cat.GetAllCategory3(cmbCategory1.SelectedValue.ToString(), "").Tables[0];
                }
            }
            cmbProductList.DisplayMember = "Name";
            cmbProductList.ValueMember = "ID";
        }

        private void cmbCategory2_SelectedValueChanged(object sender, EventArgs e)
        {

            if (cmbCategory2.Items.Count == 0) cmbCategory2.DataSource = cat.GetAllCategory2("").Tables[0];
            else
            {
                if (cmbCategory2.SelectedValue.ToString() == "1")
                {
                    cmbCategory3.DataSource = cat.GetAllCategory3("", "").Tables[0];
                }
                else
                {
                    cmbCategory3.DataSource = cat.GetAllCategory3("", cmbCategory2.SelectedValue.ToString()).Tables[0];
                }
            }

        }

        private void cmbCategory3_SelectedValueChanged(object sender, EventArgs e)
        {
            
            if (cmbCategory3.Items.Count == 0) cmbCategory3.DataSource = cat.GetAllCategory3("", "").Tables[0];
            if (cmbCategory2.SelectedValue.ToString()!="System.Data.DataRowView")
                if (cmbCategory3.SelectedValue.ToString() != "System.Data.DataRowView")
                {

                    table = prod.GetProductFromDB(cmbCategory1.SelectedValue.ToString(), cmbCategory2.SelectedValue.ToString(), cmbCategory3.SelectedValue.ToString());
                    cmbProductList.Text = "";
                    cmbProductList.DataSource = table.Tables[0];
                    cmbProductList.Update();
                }
        }

        private void btnEditRemove_Click(object sender, EventArgs e)
        {

            if (dgvProductsList.SelectedRows.Count != 0)
            {
                cmbProductList.SelectedValue = dgvProductsList.SelectedRows[0].Cells[6].Value;
                txtQuantity.Text = dgvProductsList.SelectedRows[0].Cells[5].Value.ToString();
                cmbWarehouses.SelectedValue = dgvProductsList.SelectedRows[0].Cells[7].Value.ToString();
                txtPrice.Text = dgvProductsList.SelectedRows[0].Cells[8].Value.ToString();
                cmbVAT.SelectedItem = dgvProductsList.SelectedRows[0].Cells[9].Value.ToString();
                txtCustoms.Text= dgvProductsList.SelectedRows[0].Cells[10].Value.ToString();
                foreach (DataGridViewRow row in dgvProductsList.SelectedRows)
                {
                    dgvProductsList.Rows.Remove(row);
                }
                Int32 i = 1;
                foreach (DataGridViewRow row in dgvProductsList.Rows)
                {
                    row.Cells[0].Value = i;
                    i++;
                }
            }
        }

        public void FillReceiveNoteProductsList(Int32 Number)
        {
            DataSet table = new DataSet();
            MySqlDataAdapter MyDA = new MySqlDataAdapter();
            string connString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;


            MySqlConnection mysqlCon = new MySqlConnection(connString);
            mysqlCon.Open();


            string sqlSelectAll = "SELECT * from receive_note_products WHERE Note_Number='"+Number+"'";
            MyDA.SelectCommand = new MySqlCommand(sqlSelectAll, mysqlCon);
            MyDA.Fill(table);
           

            foreach (DataRow row in table.Tables[0].Rows)
            {
                DataSet prod1 = prod.GetProductFromDBAsDataSet(Convert.ToInt32(row.ItemArray[1]));
                object[] product = new object[13];
                product[0] = row.ItemArray[4];
                product[1] = prod1.Tables[0].Rows[0].ItemArray[5];
                product[2] = prod1.Tables[0].Rows[0].ItemArray[4];
                product[3] = prod1.Tables[0].Rows[0].ItemArray[10];
                product[4] = prod1.Tables[0].Rows[0].ItemArray[11];
                product[5] = row.ItemArray[2];
                product[6] = row.ItemArray[1];
                product[7] = row.ItemArray[5];
                product[8] = Convert.ToDecimal(row.ItemArray[6]).ToString("#.00");
                product[9] = Convert.ToDecimal(row.ItemArray[7]).ToString("#.#");
                product[10] = row.ItemArray[8]; //Convert.ToDecimal(row.ItemArray[8]).ToString("#.00");
                try
                {

                    product[11] = Convert.ToDecimal(row.ItemArray[9]).ToString("N2");
                    product[12] = (Convert.ToDecimal(row.ItemArray[9]) * Convert.ToInt32(row.ItemArray[2])).ToString("N2");
                    TotalPriceMKD += Convert.ToDecimal(row.ItemArray[9]) * Convert.ToInt32(row.ItemArray[2]);
                    TotalPriceValute += Convert.ToDecimal(row.ItemArray[6]) * Convert.ToInt32(row.ItemArray[2]);
                }
                catch
                {
                    product[11] = "Не е пресметано";
                    product[12] = "Не е пресметано";
                }

                dgvProductsList.Rows.Add(product);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            btnToStCalculate_Click(sender, e);
            prod.DeleteAllProductsFromReceiveNoteList(NoteNumber);

            string connString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
            
            MySqlConnection mysqlCon = new MySqlConnection(connString);

            mysqlCon.Open();

            foreach (DataGridViewRow row in dgvProductsList.Rows)
            {

                string sqlInsertProduct = "INSERT INTO receive_note_products VALUES (DEFAULT,'" +
                                            Convert.ToInt32(row.Cells[6].Value) + "','" +
                                            Convert.ToInt32(row.Cells[5].Value) + "','" +
                                            NoteNumber + "','" +
                                            Convert.ToInt32(row.Cells[0].Value) + "','" +
                                            row.Cells[7].Value.ToString() + "',@Price,@VAT,@Customs,@AvPriceMKD)";
                MySqlCommand cmd = new MySqlCommand(sqlInsertProduct, mysqlCon);
                if (InvoiceNo == "Повратница")
                    cmd.Parameters.Add("@Price", MySqlDbType.Double, 50).Value = prod.GetAvgPriceFromWarehouse(Convert.ToInt32(row.Cells[6].Value));
                else
                cmd.Parameters.Add("@Price", MySqlDbType.Double, 50).Value = row.Cells[8].Value.ToString();
                cmd.Parameters.Add("@VAT", MySqlDbType.Double, 50).Value = row.Cells[9].Value.ToString();
                cmd.Parameters.Add("@Customs", MySqlDbType.Double, 50).Value = row.Cells[10].Value.ToString();
                try
                {
                    Convert.ToDouble(row.Cells[11].Value.ToString());
                    cmd.Parameters.Add("@AvPriceMKD", MySqlDbType.Double, 50).Value = row.Cells[11].Value.ToString();
                }
                catch
                {
                cmd.Parameters.Add("@AvPriceMKD", MySqlDbType.Double, 50).Value = 0.ToString();
                }
                cmd.ExecuteNonQuery();
            }
            
            mysqlCon.Close();
            
            this.Dispose();
            DataGridView tmp = new DataGridView();
            tmp.RowCount = 1;
            tmp.ColumnCount = 1;
            tmp.Rows[0].Cells[0].Value = Import;
            Program.GetMainForm.ShowControl(ControlsEnum.RECEIVE_NOTE_CONTROL, tmp.Rows[0]);
        }

        private void SaveNoExit()
        {
            prod.DeleteAllProductsFromReceiveNoteList(NoteNumber);

            string connString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;

            MySqlConnection mysqlCon = new MySqlConnection(connString);

            mysqlCon.Open();

            foreach (DataGridViewRow row in dgvProductsList.Rows)
            {

                string sqlInsertProduct = "INSERT INTO receive_note_products VALUES (DEFAULT,'" +
                                            Convert.ToInt32(row.Cells[6].Value) + "','" +
                                            Convert.ToInt32(row.Cells[5].Value) + "','" +
                                            NoteNumber + "','" +
                                            Convert.ToInt32(row.Cells[0].Value) + "','" +
                                            row.Cells[7].Value.ToString() + "',@Price,@VAT,@Customs,@AvPriceMKD)";
                MySqlCommand cmd = new MySqlCommand(sqlInsertProduct, mysqlCon);
                if (InvoiceNo == "Повратница")
                    cmd.Parameters.Add("@Price", MySqlDbType.Double, 50).Value = prod.GetAvgPriceFromWarehouse(Convert.ToInt32(row.Cells[6].Value));
                else
                    cmd.Parameters.Add("@Price", MySqlDbType.Double, 50).Value = row.Cells[8].Value.ToString();
                cmd.Parameters.Add("@VAT", MySqlDbType.Double, 50).Value = row.Cells[9].Value.ToString();
                cmd.Parameters.Add("@Customs", MySqlDbType.Double, 50).Value = row.Cells[10].Value.ToString();
               try
                {
                    Convert.ToDouble(row.Cells[11].Value.ToString());
                    cmd.Parameters.Add("@AvPriceMKD", MySqlDbType.Double, 50).Value = row.Cells[11].Value.ToString();
                }
                catch
                {
                cmd.Parameters.Add("@AvPriceMKD", MySqlDbType.Double, 50).Value = 0.ToString();
                }
                cmd.ExecuteNonQuery();
            }

            mysqlCon.Close();
            
        }

        public void FillWarehouses()
        {
            MySqlDataAdapter MyDA = new MySqlDataAdapter();
            DataSet table = new DataSet();
            string connString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
            MySqlConnection mysqlCon = new MySqlConnection(connString);
            mysqlCon.Open();
            string sqlSelectAll = "SELECT * from warehouses";
            MyDA.SelectCommand = new MySqlCommand(sqlSelectAll, mysqlCon);
            MyDA.Fill(table);
            mysqlCon.Close();
            table.Tables[0].Rows[0].Delete();
            cmbWarehouses.DataSource = table.Tables[0];
           

        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            TotalCustoms = 0;
            TotalVAT = 0;
            if (print)
            {
                dgvProductsList.Visible = true;
                grbAddProduct.Visible = true;
                btnAdd.Visible = true;
                btnEditRemove.Visible = true;
                print = false;
                rpvStocktakingReport.Visible = false;
            }
            else
            {
                dgvProductsList.Visible = false;
                grbAddProduct.Visible = false;
                btnAdd.Visible =false;
                btnEditRemove.Visible = false;
                print = true;
                rpvStocktakingReport.Visible = true;

                Decimal TotalPrice = 0;
               

                if (Import == 0)
                {
                    rpvStocktakingReport.Reset();
                    rpvStocktakingReport.LocalReport.ReportPath = "ReceiveNoteReport.rdlc";
                    ReceiveNoteSet ds = new ReceiveNoteSet();

                    foreach (DataGridViewRow row in dgvProductsList.Rows)
                    {
                        TotalPrice += (Convert.ToDecimal(row.Cells[5].Value) * Convert.ToDecimal(row.Cells[8].Value));
                        TotalVAT += (Convert.ToDecimal(row.Cells[5].Value) * Convert.ToDecimal(row.Cells[9].Value) * Convert.ToDecimal(row.Cells[8].Value))/100;

                        ds.Tables[0].Rows.Add(new object[] { row.Cells[0].Value.ToString(), row.Cells[1].Value.ToString(), row.Cells[3].Value.ToString(), Convert.ToInt32(row.Cells[5].Value).ToString(), row.Cells[7].Value.ToString(), Convert.ToDecimal(row.Cells[8].Value).ToString("N2"),Convert.ToInt32(row.Cells[9].Value).ToString(), row.Cells[10].Value.ToString(), (Convert.ToDecimal(row.Cells[5].Value) * Convert.ToDecimal(row.Cells[8].Value)).ToString("N2") });
                    }
                    rpvStocktakingReport.RefreshReport();
                    ReportParameter Date = new ReportParameter("Date", NoteDate.ToString("dd-MM-yyyy"));
                    ReportParameter ActiveUserPar = new ReportParameter("ActiveUser", Responsible);
                    ReportParameter NNumber = new ReportParameter("NoteNumber", NoteNumber.ToString());
                    ReportParameter PartnerPar = new ReportParameter("Partner", PartnerName);
                    ReportParameter PartnerAddressPar = new ReportParameter("PartnerAdress", PartnerAddress);
                    ReportParameter TotalPricePar = new ReportParameter("Price", TotalPrice.ToString("N2"));
                    ReportParameter TotalVATPar = new ReportParameter("VAT", TotalVAT.ToString("N2"));
                    ReportParameter PriceAndVATPar = new ReportParameter("PriceAndVAT", (Convert.ToInt32(TotalVAT+TotalPrice)).ToString("N2"));
                    ReportParameter Invoice = new ReportParameter("InvoiceNo", InvoiceNo.ToString());
                   
                    ReportDataSource rds = new ReportDataSource("DS1", ds.Tables[0]);
                    this.rpvStocktakingReport.LocalReport.DataSources.Add(rds);
                    this.rpvStocktakingReport.LocalReport.SetParameters(Date);
                    this.rpvStocktakingReport.LocalReport.SetParameters(ActiveUserPar);
                    this.rpvStocktakingReport.LocalReport.SetParameters(NNumber);
                    this.rpvStocktakingReport.LocalReport.SetParameters(PartnerPar);
                    this.rpvStocktakingReport.LocalReport.SetParameters(PartnerAddressPar);
                    this.rpvStocktakingReport.LocalReport.SetParameters(TotalPricePar);
                    this.rpvStocktakingReport.LocalReport.SetParameters(TotalVATPar);
                    this.rpvStocktakingReport.LocalReport.SetParameters(PriceAndVATPar);
                    this.rpvStocktakingReport.LocalReport.SetParameters(Invoice);
                   
                    this.rpvStocktakingReport.RefreshReport();
                }
                else
                {
                    TotalVAT = 0;
                    rpvStocktakingReport.Reset();
                    rpvStocktakingReport.LocalReport.ReportPath = "ImportReceiveNoteReport.rdlc";
                    ReceiveNoteSet ds = new ReceiveNoteSet();
                    foreach (DataGridViewRow row in dgvProductsList.Rows)
                    {
                        Decimal Customs = (((Convert.ToDecimal(row.Cells[8].Value) / TotalPriceValute) * Transport + Course * Convert.ToDecimal(row.Cells[8].Value)) * ((Convert.ToDecimal(row.Cells[10].Value)))) / 100;
                        TotalCustoms += Customs* (Convert.ToInt32(row.Cells[5].Value));
                        TotalVAT += (Customs + (Convert.ToDecimal(row.Cells[8].Value) / TotalPriceValute) * Transport + Course * Convert.ToDecimal(row.Cells[8].Value)) * (Convert.ToInt32(row.Cells[5].Value)) * Convert.ToDecimal(row.Cells[9].Value)/100;
                        
                        ds.Tables[0].Rows.Add(new object[] { row.Cells[0].Value.ToString(), row.Cells[1].Value.ToString(), row.Cells[3].Value.ToString(), row.Cells[5].Value.ToString(), row.Cells[7].Value.ToString(), Convert.ToDecimal(row.Cells[8].Value).ToString("N2"), Convert.ToDecimal(row.Cells[9].Value).ToString("#."), Convert.ToDecimal(row.Cells[10].Value).ToString("N2"),"0", Convert.ToDecimal(row.Cells[11].Value).ToString("N2"), Convert.ToDecimal(row.Cells[12].Value).ToString("N2") });
                    }

                    
                    
                    ReportParameter Date = new ReportParameter("Date", NoteDate.ToString("dd-MM-yyyy"));
                    ReportParameter ActiveUserPar = new ReportParameter("ActiveUser", Responsible);
                    ReportParameter NNumber = new ReportParameter("NoteNumber", NoteNumber.ToString());
                    ReportParameter PartnerPar = new ReportParameter("Partner", PartnerName);
                    ReportParameter PartnerAddressPar = new ReportParameter("PartnerAdress", PartnerAddress);
                    ReportParameter ValutePar = new ReportParameter("Valute", Valute);
                    ReportParameter CoursePar = new ReportParameter("Course", Course.ToString());
                    ReportParameter TransportPar = new ReportParameter("Transport", Transport.ToString("N2"));
                    ReportParameter SpeditionPar = new ReportParameter("Spedition", Spedition.ToString("N2"));
                    ReportParameter WarehousingPar = new ReportParameter("Warehousing", Warehousing.ToString("N2"));
                    ReportParameter TotalPricePar = new ReportParameter("TotalPrice", TotalPriceMKD.ToString("N2"));
                    ReportParameter TotalPriceValutePar = new ReportParameter("TotalPriceValute", TotalPriceValute.ToString("N2"));
                    ReportParameter TotalCustomsPar = new ReportParameter("TotalCustoms", TotalCustoms.ToString("N2"));
                    ReportParameter TotalVATPar = new ReportParameter("TotalVAT", TotalVAT.ToString("N2"));


                    ReportDataSource rds = new ReportDataSource("DS1", ds.Tables[0]);
                    this.rpvStocktakingReport.LocalReport.DataSources.Add(rds);
                    this.rpvStocktakingReport.LocalReport.SetParameters(Date);
                    this.rpvStocktakingReport.LocalReport.SetParameters(ActiveUserPar);
                    this.rpvStocktakingReport.LocalReport.SetParameters(NNumber);
                    this.rpvStocktakingReport.LocalReport.SetParameters(PartnerPar);
                    this.rpvStocktakingReport.LocalReport.SetParameters(PartnerAddressPar);
                    this.rpvStocktakingReport.LocalReport.SetParameters(ValutePar);
                    this.rpvStocktakingReport.LocalReport.SetParameters(CoursePar);
                    this.rpvStocktakingReport.LocalReport.SetParameters(TransportPar);
                    this.rpvStocktakingReport.LocalReport.SetParameters(SpeditionPar);
                    this.rpvStocktakingReport.LocalReport.SetParameters(WarehousingPar);
                    this.rpvStocktakingReport.LocalReport.SetParameters(TotalPricePar);
                    this.rpvStocktakingReport.LocalReport.SetParameters(TotalPriceValutePar);
                    this.rpvStocktakingReport.LocalReport.SetParameters(TotalCustomsPar);
                    this.rpvStocktakingReport.LocalReport.SetParameters(TotalVATPar);
                    this.rpvStocktakingReport.RefreshReport();

                    System.Drawing.Printing.PageSettings pg = new System.Drawing.Printing.PageSettings();
                    pg.Margins.Top = 30;
                    pg.Margins.Bottom = 30;
                    pg.Margins.Left = 30;
                    pg.Margins.Right = 30;
                    pg.Landscape = true;
                    System.Drawing.Printing.PaperSize size = new System.Drawing.Printing.PaperSize();
                    size.RawKind = (int)System.Drawing.Printing.PaperKind.A4;
                    pg.PaperSize = size;
                    rpvStocktakingReport.SetPageSettings(pg);
                    rpvStocktakingReport.RefreshReport();
                }
                
            }
        }

        private void btnToStCalculate_Click(object sender, EventArgs e)
        {
                
                SaveNoExit();
                prod.CalculateImportReceiveNote(NoteNumber);
                dgvProductsList.Rows.Clear();
                FillReceiveNoteProductsList(NoteNumber);

                TotalPriceValute = 0;
                TotalVAT = 0;
                TotalPriceMKD = 0;
                TotalCustoms = 0;
                if (Import == 0)
                {
                    rpvStocktakingReport.Reset();
                    rpvStocktakingReport.LocalReport.ReportPath = "ReceiveNoteReport.rdlc";
                    ReceiveNoteSet ds = new ReceiveNoteSet();

                    foreach (DataGridViewRow row in dgvProductsList.Rows)
                    {
                        TotalPriceMKD += (Convert.ToDecimal(row.Cells[5].Value) * Convert.ToDecimal(row.Cells[8].Value));
                        TotalVAT += (Convert.ToDecimal(row.Cells[5].Value) * Convert.ToDecimal(row.Cells[9].Value) * Convert.ToDecimal(row.Cells[8].Value)) / 100;

                        ds.Tables[0].Rows.Add(new object[] { row.Cells[0].Value.ToString(), row.Cells[1].Value.ToString(), row.Cells[3].Value.ToString(), Convert.ToInt32(row.Cells[5].Value).ToString(), row.Cells[7].Value.ToString(), Convert.ToDecimal(row.Cells[8].Value).ToString("N2"), Convert.ToInt32(row.Cells[9].Value).ToString(), row.Cells[10].Value.ToString(), (Convert.ToDecimal(row.Cells[5].Value) * Convert.ToDecimal(row.Cells[8].Value)).ToString("N2") });
                    }
                    txtTotalMKD.Text = TotalPriceMKD.ToString("N2");
                    txtTotalVAT.Text = TotalVAT.ToString("N2");

                   
                }
                else
                {
                    TotalVAT = 0;
                    TotalPriceValute = 0;
                    foreach (DataGridViewRow row in dgvProductsList.Rows)
                    {
                        
                        TotalPriceValute+=Convert.ToDecimal(row.Cells[8].Value)*Convert.ToInt32(row.Cells[5].Value);

                    }

                    foreach (DataGridViewRow row in dgvProductsList.Rows)
                    {
                        Decimal Customs = (((Convert.ToDecimal(row.Cells[8].Value) / TotalPriceValute) * Transport + Course * Convert.ToDecimal(row.Cells[8].Value)) * ((Convert.ToDecimal(row.Cells[10].Value)))) / 100;
                        TotalCustoms += Customs*(Convert.ToInt32(row.Cells[5].Value));
                        TotalVAT += (Customs + (Convert.ToDecimal(row.Cells[8].Value) / TotalPriceValute) * Transport + Course * Convert.ToDecimal(row.Cells[8].Value)) * (Convert.ToInt32(row.Cells[5].Value)) * Convert.ToDecimal(row.Cells[9].Value) / 100;
                        TotalPriceMKD += Convert.ToDecimal(row.Cells[11].Value) * Convert.ToInt32(row.Cells[5].Value);
                    }
                    txtTotalCustoms.Text = TotalCustoms.ToString("N2");
                    txtTotalValute.Text = TotalPriceValute.ToString("N2");
                    txtTotalMKD.Text = TotalPriceMKD.ToString("N2");
                    txtTotalVAT.Text = TotalVAT.ToString("N2");
                    
                }

            
        }

        private void btnPriceless_Click(object sender, EventArgs e)
        {
            if (print)
            {
                dgvProductsList.Visible = true;
                grbAddProduct.Visible = true;
                btnAdd.Visible = true;
                btnEditRemove.Visible = true;
                print = false;
                rpvStocktakingReport.Visible = false;
            }
            else
            {
                dgvProductsList.Visible = false;
                grbAddProduct.Visible = false;
                btnAdd.Visible = false;
                btnEditRemove.Visible = false;
                print = true;
                rpvStocktakingReport.Visible = true;
            }
            rpvStocktakingReport.Reset();
            rpvStocktakingReport.LocalReport.ReportPath = @"PricelessReceiveNoteReport.rdlc";
            
            ReceiveNoteSet ds = new ReceiveNoteSet();
            foreach (DataGridViewRow row in dgvProductsList.Rows)
            {
                ds.Tables[0].Rows.Add(new object[] { row.Cells[0].Value.ToString(), row.Cells[1].Value.ToString(), row.Cells[3].Value.ToString(), row.Cells[5].Value.ToString(), row.Cells[7].Value.ToString(), row.Cells[8].Value.ToString(), row.Cells[9].Value.ToString() });
            }
            rpvStocktakingReport.RefreshReport();
            ReportParameter Date = new ReportParameter("Date", NoteDate.ToString("dd-MM-yyyy"));
            ReportParameter ActiveUserPar = new ReportParameter("ActiveUser", Responsible);
            ReportParameter NNumber = new ReportParameter("NoteNumber", NoteNumber.ToString());
            ReportParameter PartnerPar = new ReportParameter("Partner", PartnerName);
            ReportParameter PartnerAddressPar = new ReportParameter("PartnerAdress", PartnerAddress);
            ReportDataSource rds = new ReportDataSource("DS1", ds.Tables[0]);
            this.rpvStocktakingReport.LocalReport.DataSources.Add(rds);
            this.rpvStocktakingReport.LocalReport.SetParameters(Date);
            this.rpvStocktakingReport.LocalReport.SetParameters(ActiveUserPar);
            this.rpvStocktakingReport.LocalReport.SetParameters(NNumber);
            this.rpvStocktakingReport.LocalReport.SetParameters(PartnerPar);
            this.rpvStocktakingReport.LocalReport.SetParameters(PartnerAddressPar);
            this.rpvStocktakingReport.RefreshReport();
        }

        private void ToStBack_Click(object sender, EventArgs e)
        {
            if (Program.GetMainForm.Back())
                this.Dispose();
        }


        private void ToStForward_Click(object sender, EventArgs e)
        {
            if (Program.GetMainForm.Forward())
                this.Dispose();
        }


    }
}
